<?php

namespace App\Traits;

use App\Events\Upload;
use App\Models\FileTransaction;
use App\Models\Qiniu;

trait WithUploadFile
{

    public function uploadFile(array $plucks = [], string $storage = 'public')
    {
        foreach ($plucks as $key => $value) {
            if (!request()->hasFile($value)) {
                continue;
            }
            $result = ['id' => 0];
            \Plupload::receive($value, function ($file) use ($storage, $value, &$result) {
                $path = \Storage::putFile($storage . '/' . $value, $file);
                try {
                    $config = Qiniu::where(['bucket' => $value])->first();
                    $fileTransaction = $this->addFile($file, $path, $config);
                    $result['id'] = $fileTransaction->id;
                } catch (\Exception $exception) {
                    \Storage::delete($path);
                }
            });
            return $result;
        }
    }

    /**
     * @param $file
     * @param $path
     * @param Qiniu|null $config
     * @return mixed
     * @throws \Throwable
     */
    protected function addFile($file, $path, ?Qiniu $config = null)
    {
        $fileTransaction = \DB::transaction(function () use ($file, $path, $config) {
            $fileTransaction = new FileTransaction();
            $fileTransaction->author_id = \Auth::user()->id;
            $fileTransaction->config_id = !empty($config) ? $config->id : null;
            $fileTransaction->name = $file->getClientOriginalName();
            $fileTransaction->path = \Storage::url($path);
            $fileTransaction->file_path = $path;
            $fileTransaction->size = $file->getSize();
            $fileTransaction->mime_type = $file->getMimeType();
            $fileTransaction->is_upload = false;
            $fileTransaction->status = true;
            $fileTransaction->save();
            if (!is_null($fileTransaction->config_id)) {
                event(new Upload($fileTransaction));
            }
            return $fileTransaction;
        });
        return $fileTransaction;
    }
}